<template>
  <el-row class="ticket-workbench-page">
    <el-row
      v-loading="listLoading"
      element-loading-text="正在加载数据..."
      class="page-left"
    >
      <!-- #region 搜索框 -->
      <el-row class="left-search">
        <el-input
          v-model="listQuery.name"
          size="mini"
          placeholder="模板名称"
          prefix-icon="el-icon-search"
          @keyup.enter.native="handleInitFilterTicket"
        >
          <!-- <template slot="prepend">{{item.name}}</template> -->
        </el-input>
      </el-row>
      <!-- #endregion -->

      <!-- #region 列表部分 -->
      <el-row class="left-list">
        <el-row v-if="ticketList.length === 0">
          <div class="el-table--mini el-table__empty-block">
            <span class="el-table__empty-text">暂无数据</span>
          </div>
        </el-row>
        <el-row
          v-for="item in ticketList"
          :key="item._id"
        >
          <el-row
            :title="item.name"
            class="left-ticket-item"
            :class="{ active: currentworksheetId === item.worksheetId }"
          >
            <el-link :underline="false" @click="handleClickTicketItem(item)">
              {{ item.name }}
            </el-link>
          </el-row>
        </el-row>
      </el-row>
      <!-- #endregion -->

      <!-- #region 分页部分 -->
      <el-row class="left-pagination">
        <el-row class="pagination-pager">
          <el-pagination
            small
            layout="pager"
            :current-page.sync="listQuery.page"
            :page-size="listQuery.limit || 10"
            :pagerCount="5"
            :total="total"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </el-row>
      </el-row>
      <!-- #endregion -->
    </el-row>

    <keep-alive>
      <el-row
        v-loading="microAppLoading"
        element-loading-text="正在加载数据..."
        class="ticket-workbench-container"
      >
        <el-row
          id="apassMicroTicketWorkbench"
          class="page-container mp-micro"
        />
      </el-row>
    </keep-alive>
  </el-row>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { TicketModule } from '@/store/modules/ticket/index'
import { loadMicroApp } from 'qiankun'
import { CommonModule } from '@/store/modules/common'
import { mpCallMsgEvent } from '@/store/modules/cti/ctiEvent'
// import { SheetSummaryModule } from '@/store/modules/microAppStore/sheetSummary'
@Component({
  name: 'ticketWorkbench'
})

export default class TicketWorkbench extends Vue {
  // #region 基础数据
  private $router: any
  private $route: any
  private $bus: any
  private currentRoute: string = ''
  private microApp: any
  private microAppLoading: boolean = false
  private ticketItemId: string = ''
  private currentworksheetId: string = ''
  private ticketList: [] = []
  private listLoading: boolean = false
  private total: number = 0
  private $store: any
  private mpData: any = {} // 小铃铛点击mp消息提醒跳转
  private listQuery = { // 查询参数的data
    name: '',
    page: 1,
    limit: 20
  }
  // #endregion

  // #region 数据初始化
  private initData (first: boolean = false) { // 获取工单列表
    this.listLoading = true
    TicketModule.TicketCommonAction({ url: '/crm/action/ticket/findName', method: 'POST', data: this.listQuery }).then(res => {
      if (res && res.success) {
        const resList = res.list || []
        this.ticketList = resList
        this.total = res.count || 0
        if (resList.length > 0) { // 有列表数据时
          if (this.ticketItemId === '') { // 第一次进来时 或 上一次没找到时
            this.handleClickTicketItem(resList[0])
          } else {
            const last = resList.find(v => v._id === this.ticketItemId)
            if (last === undefined) { // 有上一次数据时
              this.handleClickTicketItem(resList[0])
            } else {
              // console.log('啥也不干')
            }
          }
        }
      }
    }).finally(() => {
      this.listLoading = false
    })
  }

  private handleInitFilterTicket () { // 初始化分页参数，并获取工单列表
    this.listQuery.page = 1
    this.initData()
  }

  private handleCurrentChange (page: number) { // 获取工单列表
    this.initData()
  }

  private handleClickTicketItem (item) { // 点击左侧某个工单
    const data = {
      worksheetName: item.name,
      applicationId: item.applicationId,
      worksheetId: this.mpData.worksheetId || item.worksheetId,
      recordId: this.mpData.recordId || '',
      viewId: this.mpData.viewId || ''
    }
    if (this.ticketItemId === '') { // 第一次点击
      this.initMicroApp(data)
    } else if (this.ticketItemId !== item._id) { // 后面的点击如果不是同一个只调用update，同一个不重新加载
      this.microApp.update({
        type: 'changeWorksheet',
        data
      })
    }
    this.ticketItemId = this.mpData.worksheetId ? '' : item._id
    this.currentworksheetId = this.mpData.worksheetId || item.worksheetId // mp的跳转，数据带翻页，当前选中的是谁无法直接匹配到，有就选中，没有就不选中
    this.mpData = {} // 传递给mp之后，要把跳转存储的数据清空
  }
  // #endregion

  // #region 子应用注册函数
  private initMicroApp (store) {
    const activeRule = '/ticket_workBench/index'
    // mopower 打电话发短信的回调事件
    this.$set(store, 'handleCallMessage', mpCallMsgEvent);
    this.$set(store, 'goTo', ({ applicationId, worksheetId, type, flowId }) => {
      // 根据不同的 type 做出不同的路由跳转
      switch (type) {
        case 'workflow': // 跳转至 模板配置-工作流列表
        case 'fields': // 跳转至 模板配置-字段设置
          this.$router.push({
            path: `/setting_center/index/customer_template_setting/edit/${this.ticketItemId}/${applicationId}/${worksheetId}/${type}`,
            query: { routerTo: type }
          })
          break;
        case 'editFlow': // 跳转至 模板设置-工作流详情配置页
          this.$router.push({
            path: `/setting_center/index/customer_template_setting/edit/${this.ticketItemId}/${applicationId}/${worksheetId}/editFlow/${flowId}`,
            query: { routerTo: `editFlow/${flowId}` }
          })
          break;
        default:
          console.error('mopower goTo 函数未知 type:', type);
          break;
      }
    })
    console.log(store, 'init传递======')
    CommonModule.getMpInfo({ url: '/auth/get/mp/relation', method: 'POST', data: {} }).then(() => {
      this.microApp = loadMicroApp(
        {
          name: 'apass-micro-ticketWorkbench',
          entry: `${(CommonModule.initConfig as any).platformConfig.mopowerUrl}/sheetSummary.html`,
          container: '#apassMicroTicketWorkbench',
          props: {
            headerHeight: -36, // 表头的高度
            // callEvent: true, // 是否展示电话字段处的[打电话、发短信]功能
            routerBase: activeRule,
            store,
            user: {
              id: this.$store.state.common.mpInfo.mpUserId,
              companyId: this.$store.state.common.mpInfo.mpCompanyId
            }
          }
        },
        {
          sandbox: {
            // experimentalStyleIsolation: true
          }
        }
      )
    })
  }

  private unmountMicroApp () {
    if (this.microApp && JSON.stringify(this.microApp) !== '{}') {
      this.microApp.mountPromise.then(() => {
        if (this.microApp.getStatus() === 'MOUNTED') {
          console.log(' this.microApp.unmount()')
          this.microApp.unmount()
        }
      })
    }
  }
  // #endregion

  // #region 生命周期钩子

  private beforeRouteLeave (to: any, from: any, next: any) {
    // 注意：为何使用window.location.pathname，原理同客户工作台
    this.currentRoute = window.location.pathname
    this.mpData = {}
    next()
  }

  private beforeRouteEnter (to: any, from: any, next: any) {
    next((vm: any) => {
      const mpData = vm.$route.query.mpData
      if (mpData) { // 第一次进入，有带着记录id存起来，用于打开mp的记录详情
        vm.mpData = JSON.parse(mpData)
      }
      if (vm.currentRoute) {
        // 点击其他模块回到当前模块离开时的模块 || 刷新系统
        vm.$router.push({ path: vm.currentRoute })
        vm.initData() // 仅刷新列表
      } else {
        vm.initData(true)
      }
    })
  }

  // #endregion
  private mounted () {
    this.$bus.$on('updateMpRecord', mpInfo => {
      if (this.microApp && mpInfo.type === 'TICKET') { // 有挂载微应用 && 是工单模板的更新
        const data = {
          worksheetName: mpInfo.name,
          applicationId: mpInfo.data.applicationId,
          worksheetId: mpInfo.data.worksheetId,
          recordId: mpInfo.data.recordId, // 记录id
          viewId: mpInfo.data.viewId // 视图id
        }
        this.microApp.update({ type: 'changeWorksheet', data })
        this.currentworksheetId = mpInfo.data.worksheetId || '' // mp的跳转，数据带翻页，当前选中的是谁无法直接匹配到，有就选中，没有就不选中
      }
    })
  }

  private beforeDestroy () {
    this.$bus.$off('updateMpRecord')
  }
}
</script>

<style lang="stylus" scoped>
  .ticket-workbench-page
    display flex
    flex-wrap nowrap
    height 100%
  .page-left
    font-size 14px
    width 150px
    height 100%
    color $fc-gray2
    font-weight bold
    box-sizing border-box
    border 1px solid $border-main
    box-shadow 0px 0px 4px 0px #E0E6F0, 0px 1px 4px 0px #E0E6F0
    border-radius 10px
    padding 4px 0px 4px 0px
    .left-search
      height 40px
      margin-top 5px
      padding 0px 10px
    .left-list
      height calc(100% - 90px)
      overflow-x hidden
      overflow-y auto
      .left-ticket-item
        padding 15px 10px
        height 45px
        &.active
          background #e5f3fd
        &.active >>> .el-link--inner
          color #409EFF
        & >>> .el-link--inner
          font-size 12px !important
          color #1f2d3d
          width 107px
          text-overflow ellipsis
          overflow hidden
          white-space nowrap
          font-weight normal
    .left-pagination
      height 40px
      padding 10px 10px
      display flex
      justify-content center
      .pagination-pager
        & >>> .el-pagination--small .el-pager li
          display initial
  .ticket-workbench-container
    flex 1
    width 100%
    height 100%
    margin-left 20px
    border 1px solid $border-main
    box-shadow 0px 0px 4px 0px #E0E6F0, 0px 1px 4px 0px #E0E6F0
    border-radius 10px
    overflow auto
    background white url('../../assets/img/loading.gif') no-repeat center center
    background-size 1.2 1.2
</style>
